#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <signal.h>
#include <fcntl.h>
#include <pthread.h>
#include <time.h>
#include "parse.h"
#include "log.h"
#include "response.h"

//服务器设置
#define MAX_CLIENTS             1000

//全局变量
char log_buf[LOG_BUF_SIZE];
int sock = -1, client_sock = -1;


int close_socket(int sock) {
    if (close(sock)) {
        fprintf(stderr, "Failed closing socket.\n");
        return 1;
    }
    return 0;
}
void handle_signal(const int sig) {
    if (sock != -1) {
        fprintf(stderr, "\nReceived signal %d. Closing socket.\n", sig);
        close_socket(sock);
    }
    exit(0);
}
void handle_sigpipe(const int sig) 
{
    if (sock != -1) {
        return;
    }
    exit(0);
}


int main(int argc, char *argv[]) {
    /* register signal handler */
    /* process termination signals */
    signal(SIGTERM, handle_signal);
    signal(SIGINT, handle_signal);
    signal(SIGSEGV, handle_signal);
    signal(SIGABRT, handle_signal);
    signal(SIGQUIT, handle_signal);
    signal(SIGTSTP, handle_signal);
    signal(SIGFPE, handle_signal);
    signal(SIGHUP, handle_signal);
    /* normal I/O event */
    signal(SIGPIPE, handle_sigpipe);

    char buf[BUF_SIZE];
    char recv_buf[BUF_SIZE * 10];  // 增加接收缓冲区大小以支持粘包处理
    ssize_t readret = 0;
    socklen_t cli_size;
    struct sockaddr_in addr, cli_addr;
    fprintf(stdout, "----- Echo Server -----\n");

    /* all networked programs must create a socket */
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "Failed creating socket.\n");
        sprintf(log_buf,"Failed creating socket.\n");
        log_write(log_buf, TRUE, 1);
        return EXIT_FAILURE;
    }
    /* set socket SO_REUSEADDR | SO_REUSEPORT */
    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        fprintf(stderr, "Failed setting socket options.\n");
        return EXIT_FAILURE;
    }

    addr.sin_family = AF_INET; // ipv4
    addr.sin_port = htons(ECHO_PORT);
    addr.sin_addr.s_addr = INADDR_ANY;

    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(sock, (struct sockaddr *) &addr, sizeof(addr))) {
        close_socket(sock);
        fprintf(stderr, "Failed binding socket.\n");
        sprintf(log_buf,"Failed binding socket.\n");
        log_write(log_buf, TRUE, 1);
        return EXIT_FAILURE;
    }

    if (listen(sock, 5)) {
        close_socket(sock);
        fprintf(stderr, "Error listening on socket.\n");
        sprintf(log_buf,"Error listening on socket.\n");
        log_write(log_buf, TRUE, 1);
        return EXIT_FAILURE;
    }

    // 使用 select 实现 IO 多路复用
    fd_set read_fds, master_fds;
    int max_fd = sock;
    FD_ZERO(&master_fds);
    FD_SET(sock, &master_fds);//将监听描述符加入集合

    int client_socks[MAX_CLIENTS] = {0};  // 存储已连接的客户端套接字
    int client_count = 0;

    while (1) {
        read_fds = master_fds;

        // 调用 select 监听文件描述符
        if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1) {
            perror("select");
            continue;
        }

        // 检查是否有新连接
        if (FD_ISSET(sock, &read_fds)) {
            cli_size = sizeof(cli_addr);
            int new_client = accept(sock, (struct sockaddr *)&cli_addr, &cli_size);
            if (new_client == -1) {
                perror("accept");
                continue;
            }

            // 将新连接的客户端套接字添加到 master_fds
            FD_SET(new_client, &master_fds);
            if (new_client > max_fd) {
                max_fd = new_client;
            }

            client_socks[client_count++] = new_client;
            printf("New connection from %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
        }

        // 检查已连接的客户端是否有数据可读
        for (int i = 0; i < client_count; i++) {
            int client_sock = client_socks[i];
            if (client_sock && FD_ISSET(client_sock, &read_fds)) {
                memset(recv_buf, 0, sizeof(recv_buf));  // 初始化接收缓冲区
                readret = recv(client_sock, buf, BUF_SIZE, 0);
                if (readret > 0) {
                    // 将接收到的数据追加到接收缓冲区
                    memcpy(recv_buf + strlen(recv_buf), buf, readret);
                    memset(buf, 0, BUF_SIZE);  // 清空临时缓冲区

                    // 解析接收缓冲区中的数据，支持管道和粘包处理
                    char *request_start = recv_buf;
                    while (1) {
                        char *request_end = strstr(request_start, "\r\n\r\n");  // 查找请求结束标志
                        if (request_end == NULL) {
                            // 如果没有找到完整的请求，则跳出循环，等待更多数据
                            break;
                        }

                        // 提取完整的请求
                        size_t request_len = request_end - request_start + 4;  // 包括末尾的 \r\n\r\n
                        char request[BUF_SIZE];
                        memcpy(request, request_start, request_len);
                        request[request_len] = '\0';

                        // 处理解析出的请求
                        parse_request(client_sock, request, request_len);

                        // 更新请求起始位置
                        request_start += request_len;
                    }

                    // 将剩余未处理的数据移动到缓冲区开头
                    size_t remaining_len = strlen(request_start);
                    memmove(recv_buf, request_start, remaining_len);
                    recv_buf[remaining_len] = '\0';
                } else if (readret == 0) {
                    // 客户端关闭连接
                    close_socket(client_sock);
                    FD_CLR(client_sock, &master_fds);
                    client_socks[i] = 0;
                    printf("Client disconnected\n");
                } else {
                    // 发生错误
                    close_socket(client_sock);
                    FD_CLR(client_sock, &master_fds);
                    client_socks[i] = 0;
                    perror("recv");
                }
            }
        }
    }

    close_socket(sock);
    return EXIT_SUCCESS;
}
